package com.voicechat.firstmet.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.SystemAndOfficialActivity;
import com.voicechat.firstmet.adapter.IMessageConversationAdapter;
import com.voicechat.firstmet.base.BaseAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.imcontrol.Conversation;
import com.voicechat.firstmet.imcontrol.ConversationPresenter;
import com.voicechat.firstmet.imcontrol.ConversationView;
import com.voicechat.firstmet.imcontrol.ILoginView;
import com.voicechat.firstmet.imcontrol.LoginHelper;
import com.voicechat.firstmet.imcontrol.MessageFactory;
import com.voicechat.firstmet.imcontrol.NomalConversation;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.SPUtils;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment_shar_girls
 * @ClassName: IMessageFragment
 * @Description: java类作用描述
 * @Author: ljp
 * @CreateDate: 2019/1/4 17:43
 * @Version: 1.0
 */
public class IMessageFragment extends BaseFragment implements ConversationView,ILoginView {
    @BindView(R.id.recycle_msg_list)
    RecyclerView recycleMsgList;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    private List<Conversation> conversationList = new LinkedList<>();
    private ConversationPresenter presenter;
    private IMessageConversationAdapter adapter;
    private String TAG = "IMessageFragment";
    private MySelfInfoBean.ObjectBean mySeleInfo;

    @Override
    protected int loadLayout() {
        return R.layout.activity_imessage;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initView();
    }

    private void initData() {
        presenter = new ConversationPresenter(this);
        presenter.getConversation();
        adapter.notifyDataSetChanged();
        refresh();
    }

    @Override
    public void onResume() {
        try {
            super.onResume();
            refresh();
        } catch (Exception e) {

        }
    }
    /**
     * @return
     * @method
     * @description 数据控件实力话
     * @date: 2018/11/12 10:07
     * @author: ljp
     */
    private void initView() {
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //presenter.getConversation();
              //  conversationList.clear();
               // initData();
                refresh();
                smartRefresh.finishRefresh(500);
            }
        });
        //上拉加载更多
        /*smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                smartRefresh.finishLoadMore(10000);
            }
        });*/
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        //smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        adapter = new IMessageConversationAdapter(activity, conversationList, R.layout.item_message_list);
        adapter.addHeaderView(R.layout.item_head_message_list);
        recycleMsgList.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleMsgList.setAdapter(adapter);
        adapter.setItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(int postion, View view) {
                conversationList.get(postion).navToDetail(activity);
            }
        });
        adapter.setItemClick(new IMessageConversationAdapter.ItemClick() {
            @Override
            public void setItemClick(String type) {
               // new MainActivity().setMsgUnread(0);
                Intent intent = new Intent(activity, SystemAndOfficialActivity.class);//跳往系统消息和官方通知页面
                intent.putExtra("type", type);
                startActivity(intent);
            }

            @Override
            public void setLongItemClick(int position) {
                NomalConversation conversation = (NomalConversation) conversationList.get(position);
                //Log.i(TAG, "setLongItemClick:---getIdentify-- "+conversation.getIdentify());
                // if (presenter.delConversation(conversation.getType(), conversation.getIdentify())){
                //   conversationList.remove(conversation);
                //  adapter.notifyDataSetChanged();
                // }
            }
        });
        String loginUser = TIMManager.getInstance().getLoginUser();//当前登录用户名
        if (!TextUtils.isEmpty(loginUser)){
            initData();
        }else {//重新登录
            LoginHelper loginHelper = new LoginHelper(this);
            loginHelper.login(mySeleInfo.getId(), SPUtils.getEditoString(SPUtils.SP_USERSIG));
        }
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Conversation conversation = conversationList.get(info.position);
        if (conversation instanceof NomalConversation) {
            menu.add(0, 1, Menu.NONE, "删除会话");
        }
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        NomalConversation conversation = (NomalConversation) conversationList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                if (conversation != null) {
                    if (presenter.delConversation(conversation.getType(), conversation.getIdentify())) {
                        conversationList.remove(conversation);
                        adapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }


    /**
     * 初始化界面或刷新界面
     *
     * @param conversationList
     */
    @Override
    public void initView(List<TIMConversation> conversationList) {
        Log.i(TAG, "initView: ----conversationList--");
      //  this.conversationList.clear();
        for (TIMConversation item : conversationList) {
            switch (item.getType()) {
                case C2C:
                   // this.conversationList.add(new NomalConversation(item));
                case Group:
                    break;
            }
        }
    }

    /**
     * 更新最新消息显示
     *
     * @param message 最后一条消息
     */
    @Override
    public void updateMessage(TIMMessage message) {
        if (message == null) {
            adapter.notifyDataSetChanged();
            return;
        }
        if (message.getConversation().getType() == TIMConversationType.System) {
            //groupManagerPresenter.getGroupManageLastMessage();
            return;
        }
        //if (MessageFactory.getMessage(message) instanceof CustomMessage) return;
        NomalConversation conversation = new NomalConversation(message.getConversation());
        conversation.getUserMessageOther(message.getConversation().getPeer());
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation c = iterator.next();
            if (conversation.equals(c)) {
                conversation = (NomalConversation) c;

                iterator.remove();
                break;
            }
        }
        //presenter.delConversation(conversation.getType(), conversation.getIdentify());
        conversation.setLastMessage(MessageFactory.getMessage(message));
        conversationList.add(conversation);
        Collections.sort(conversationList);
        //adapter.notifyDataSetChanged();
        refresh();
    }

    /**
     * 删除会话
     *
     * @param identify
     */
    @Override
    public void removeConversation(String identify) {
    }

    /**
     * 刷新
     */
    @Override
    public void refresh() {
        Collections.sort(conversationList);
        adapter.notifyDataSetChanged();
        smartRefresh.finishRefresh();
    }

    /**
     * @return
     * @method
     * @description 获取未读消息数量
     * @date: 2018/12/17 10:43
     * @author: ljp
     */
    private long getTotalUnreadNum() {
        long num = 0;
        for (Conversation conversation : conversationList) {
            num += conversation.getUnreadNum();
        }
        return num;
    }

    @Override
    public void updateLoginState(boolean state) {

    }

    @Override
    public void onLoginSDKSuccess() {
        initData();
    }

    @Override
    public void onLoginSDKFailed(int errCode, String errMsg) {

    }

    @Override
    public void onLogoutSDKSuccess() {

    }

    @Override
    public void onLogoutSDKFailed(int errCode, String errMsg) {

    }
}
